package com.gpoint.rdp.card.department.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.gpoint.rdp.card.department.persistence.entity.DepartmentExcelEntity;
import com.gpoint.rdp.card.department.persistence.entity.DepartmentPo;
import com.gpoint.rdp.card.department.repository.DepartmentRepository;
import com.gpoint.rdp.card.department.service.DepartmentQueryService;
import com.gpoint.rdp.card.department.service.DepartmentService;
import com.gpoint.rdp.api.base.context.CurrentContext;
import com.gpoint.rdp.api.base.query.QueryFilter;
import com.gpoint.rdp.base.core.entity.ResultMessage;
import com.gpoint.rdp.base.core.exception.BaseException;
import com.gpoint.rdp.base.core.util.BeanUtils;
import com.gpoint.rdp.base.core.util.string.StringUtil;
import com.gpoint.rdp.base.framework.page.PageList;
import com.gpoint.rdp.base.framework.page.PageResult;
import com.gpoint.rdp.base.web.controller.GenericController;
import com.gpoint.rdp.base.web.json.PageJson;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/card/department/departmentImport/")
public class DepartmentImportController extends GenericController {

    @Resource
    private CurrentContext currentContext;

    @Resource
    private DepartmentQueryService departmentQueryService;

    @Resource
    private DepartmentService departmentService;

//    @Resource
//    private DepartmentRepository departmentRepository;

    /**
     * 导入失败数据缓存
     */
    private static List < DepartmentExcelEntity > FAILLIST;

    /**
     * 文件导入
     *
     * @param request
     * @param response
     * @param file
     * @throws Exception
     */
//    @RequestMapping("action_import")
//    public void actionImport(HttpServletRequest request, HttpServletResponse response,
//            @RequestParam("file") CommonsMultipartFile file) throws Exception {
//        ResultMessage message = null;
//        try {
//            // 初始化缓存
//            FAILLIST = new ArrayList <>();
//            // 读出文件
//            if (BeanUtils.isEmpty(file)) {
//                throw new BaseException("文件缺失");
//            }
//            String filePath = file.getOriginalFilename();
//            if (StringUtil.isEmpty(filePath)) {
//                throw new BaseException("文件路径错误");
//            }
//            List < DepartmentExcelEntity > excelList = null;
//            InputStream in = file.getInputStream();
//            if (BeanUtils.isEmpty(in)) {
//                throw new BaseException("读取文件数据失败");
//            }
//            else {
//                Workbook wb = ImportExcelUtil.chooseWorkbook(filePath, in);
//                if (BeanUtils.isNotEmpty(wb)) {
//                    try {
//                        excelList = ImportExcelUtil.readDateListT(wb, new DepartmentExcelEntity(), 3, 0);
//                    }
//                    catch (Exception e) {
//                        throw new BaseException("文件解析失败");
//                    }
//                }
//            }
//            // excel文件中数据校验
//            List < DepartmentExcelEntity > excelcheckList = checkExcel(excelList);
//            int dbokRows = 0;
//            Date timenow = new Date();
//
//            Map < String, List < DepartmentExcelEntity > > group = getGroupExist(excelcheckList);
//            String servicecode = MyConfig.SERVICE_CODE;
//            List < DepartmentPo > insertList = new ArrayList <>();
//            Map < String, String > dbMap;
//            if (BeanUtils.isNotEmpty(excelcheckList)) {
//                for (Map.Entry < String, List < DepartmentExcelEntity > > m : group.entrySet()) {
//                    String academy = m.getKey();
//                    List < DepartmentPo > dbList = departmentQueryService.queryChildList(servicecode, academy);
//                    dbMap = new HashMap <>();
//                    if (BeanUtils.isNotEmpty(dbList)) {
//                        for (int i = 0; i < dbList.size(); i++) {
//                            if (dbList.get(i).getTypecode().equals("grade"))
//                                dbMap.put(dbList.get(i).getOrgname() + dbList.get(i).getParentcode(),
//                                        dbList.get(i).getId());
//                            else
//                                dbMap.put(dbList.get(i).getOrgname(), dbList.get(i).getId());
//                        }
//                    }
//                    List < DepartmentExcelEntity > valueList = m.getValue();
//                    Map < String, DepartmentPo > tempMap = new HashMap < String, DepartmentPo >();
//                    for (int i = 0; i < valueList.size(); i++) {
//                        DepartmentExcelEntity entity = valueList.get(i);
//                        DepartmentPo departmentPo;
//                        int academyid;
//                        int majorid;
//                        int gradeid;
//                        int classid;
//                        if (!tempMap.containsKey(entity.getAcademy())) {
//                            if (dbMap.containsKey(entity.getAcademy()))
//                                academyid = Integer.parseInt(dbMap.get(entity.getAcademy()));
//                            else {
//                                academyid = departmentQueryService.getSeq();
//                                departmentPo = new DepartmentPo();
//                                departmentPo.setId(String.valueOf(academyid));
//                                departmentPo.setOrgcode(String.valueOf(academyid));
//                                departmentPo.setOrgname(entity.getAcademy());
//                                departmentPo.setServicecode(servicecode);
//                                departmentPo.setTypecode("academy");
//                                departmentPo.setFlag(1l);
//                                departmentPo.setCreatetime(timenow);
//                                departmentPo.setCreateuser(currentContext.getCurrentUserId());
//                                insertList.add(departmentPo);
//                                tempMap.put(entity.getAcademy(), departmentPo);
//                            }
//                        }
//                        else {
//                            academyid = Integer.parseInt(tempMap.get(entity.getAcademy()).getId());
//                        }
//                        if (StringUtil.isEmpty(entity.getMajor()))
//                            continue;
//                        if (!tempMap.containsKey(entity.getMajor())) {
//                            if (dbMap.containsKey(entity.getMajor()))
//                                majorid = Integer.parseInt(dbMap.get(entity.getMajor()));
//                            else {
//                                majorid = departmentQueryService.getSeq();
//                                departmentPo = new DepartmentPo();
//                                departmentPo.setId(String.valueOf(majorid));
//                                departmentPo.setOrgcode(String.valueOf(majorid));
//                                departmentPo.setParentcode(String.valueOf(academyid));
//                                departmentPo.setOrgname(entity.getMajor());
//                                departmentPo.setServicecode(servicecode);
//                                departmentPo.setTypecode("major");
//                                departmentPo.setFlag(1l);
//                                departmentPo.setCreatetime(timenow);
//                                departmentPo.setCreateuser(currentContext.getCurrentUserId());
//                                insertList.add(departmentPo);
//                                tempMap.put(entity.getMajor(), departmentPo);
//                            }
//                        }
//                        else {
//                            majorid = Integer.parseInt(tempMap.get(entity.getMajor()).getId());
//                        }
//                        if (StringUtil.isEmpty(entity.getGrade()))
//                            continue;
//                        if (!tempMap.containsKey(entity.getGrade() + majorid)) {
//                            if (dbMap.containsKey(entity.getGrade() + majorid))
//                                gradeid = Integer.parseInt(dbMap.get(entity.getGrade() + majorid));
//                            else {
//                                gradeid = departmentQueryService.getSeq();
//                                departmentPo = new DepartmentPo();
//                                departmentPo.setId(String.valueOf(gradeid));
//                                departmentPo.setOrgcode(String.valueOf(gradeid));
//                                departmentPo.setParentcode(String.valueOf(majorid));
//                                departmentPo.setOrgname(entity.getGrade());
//                                departmentPo.setServicecode(servicecode);
//                                departmentPo.setTypecode("grade");
//                                departmentPo.setFlag(1l);
//                                departmentPo.setCreatetime(timenow);
//                                departmentPo.setCreateuser(currentContext.getCurrentUserId());
//                                insertList.add(departmentPo);
//                                tempMap.put(entity.getGrade() + majorid, departmentPo);
//                            }
//                        }
//                        else {
//                            gradeid = Integer.parseInt(tempMap.get(entity.getGrade() + majorid).getId());
//                        }
//                        if (StringUtil.isEmpty(entity.getClassname()))
//                            continue;
//                        if (dbMap.containsKey(entity.getClassname())) {
//                            entity.setRemark("该班级已存在");
//                            FAILLIST.add(entity);
//                        }
//                        else {
//                            classid = departmentQueryService.getSeq();
//                            departmentPo = new DepartmentPo();
//                            departmentPo.setId(String.valueOf(classid));
//                            departmentPo.setOrgcode(String.valueOf(classid));
//                            departmentPo.setParentcode(String.valueOf(gradeid));
//                            departmentPo.setOrgname(entity.getClassname());
//                            departmentPo.setServicecode(servicecode);
//                            departmentPo.setTypecode("class");
//                            departmentPo.setFlag(1l);
//                            departmentPo.setCreatetime(timenow);
//                            departmentPo.setCreateuser(currentContext.getCurrentUserId());
//                            insertList.add(departmentPo);
//                            tempMap.put(entity.getClassname(), departmentPo);
//                        }
//                    }
//                }
//                departmentRepository.addByList(insertList);
//                dbokRows = excelList.size() - FAILLIST.size();
//                // 组织返回
//                Map < String, Object > returnMap = new HashMap <>();
//                returnMap.put("rows", dbokRows);
//                message = new ResultMessage(ResultMessage.SUCCESS, "成功");
//                message.setVars(returnMap);
//            }
//            else {
//                message = new ResultMessage(ResultMessage.FAIL, "专业或年级不能为空");
//            }
//        }
//        catch (Exception e) {
//            message = new ResultMessage(ResultMessage.FAIL, "操作失败,", e.getMessage());
//            logger.error("操作失败,", e.getMessage(), e);
//        }
//        writeResultMessage(response.getWriter(), message);
//    }

    /**
     * excel数据校验
     *
     * @param listExcel
     * @return
     */
    private List < DepartmentExcelEntity > checkExcel(List < DepartmentExcelEntity > excelList) {
        List < DepartmentExcelEntity > excelOkList = new ArrayList <>();
        for (DepartmentExcelEntity po : excelList) {
            String error = "";
            if (StringUtil.isEmpty(po.getAcademy())) {
                error += "院系为空;";
            }
            if (StringUtil.isEmpty(po.getMajor())
                    && (StringUtil.isNotEmpty(po.getGrade()) || StringUtil.isNotEmpty(po.getClassname()))) {
                error += "专业为空;";
            }
            if (StringUtil.isEmpty(po.getGrade()) && StringUtil.isNotEmpty(po.getClassname())) {
                error += "年级级为空;";
            }
            if (StringUtil.isNotEmpty(error)) {
                po.setRemark(error);
                FAILLIST.add(po);
            }
            else {
                excelOkList.add(po);
            }
        }
        return excelOkList;
    }

    /**
     * 根据院系分组
     *
     * @param type
     * @param serviceCode
     * @param listExisted
     * @return
     */
    private Map < String, List < DepartmentExcelEntity > > getGroupExist(List < DepartmentExcelEntity > dataList) {
        Map < String, List < DepartmentExcelEntity > > map = new HashMap <>(256);
        List < DepartmentExcelEntity > list;
        for (int i = 0; i < dataList.size(); i++) {
            if (map.containsKey(dataList.get(i).getAcademy())) {
                list = map.get(dataList.get(i).getAcademy());
                list.add(dataList.get(i));
                map.put(dataList.get(i).getAcademy(), list);
            }
            else {
                list = new ArrayList <>();
                list.add(dataList.get(i));
                map.put(dataList.get(i).getAcademy(), list);
            }
        }
        return map;
    }

    /**
     * 返回json列表
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("listPage")
    @ResponseBody
    public PageJson listPage(HttpServletRequest request, HttpServletResponse response) {
        try {
            List < DepartmentExcelEntity > cList = FAILLIST;
            QueryFilter queryFilter = getQuerFilter(request);
            int pageSize = queryFilter.getPage().getPageSize();
            int page = queryFilter.getPage().getPageNo();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("limit", pageSize);
            jsonObject.put("page", page);
            if (BeanUtils.isNotEmpty(cList)) {
                int total = cList.size();
                jsonObject.put("totalCount", total);
                int fromIndex = (int) (pageSize * (page - 1));
                int toIndex = pageSize * page > total ? total : (int) (pageSize * page);
                cList = cList.subList(fromIndex, toIndex);
            }
            else {
                cList = new ArrayList <>();
            }
            PageResult result = PageResult.fromJson(jsonObject.toString());
            PageList < DepartmentExcelEntity > pageList = null;
            pageList = new PageList < DepartmentExcelEntity >(cList, result);
            return new PageJson(pageList);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new PageJson();
        }
    }

    /**
     * 清空缓存数据
     *
     * @param request
     * @param response
     */
    @RequestMapping("action_clear")
    public void actionClear(HttpServletRequest request, HttpServletResponse response) {
        FAILLIST = new ArrayList <>();
    }

    /**
     * 下载模板excel
     *
     * @param resp
     * @param req
     * @return
     * @throws Exception
     */
//    @RequestMapping("action_download")
//    public ResponseEntity < byte[] > actionDownLoad(HttpServletResponse resp, HttpServletRequest req) throws Exception {
//        File file = ResourceUtils.getFile(JasperReportUtil.class.getClassLoader().getResource("/").getPath()
//                + "excelTemplate/tmp_import_class.xls");
//        return ResponseUtils.buildResponseEntity(file);
//    }
//
//    @RequestMapping("action_export")
//    public void actionExportExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        List < Map < String, Object > > list = new ArrayList <>();
//        List < DepartmentExcelEntity > subExcelEntities = FAILLIST;
//        Map < String, Object > map = new HashMap <>();
//        if (BeanUtils.isNotEmpty(subExcelEntities)) {
//            for (int i = 0; i < subExcelEntities.size(); i++) {
//                String academy = subExcelEntities.get(i).getAcademy();
//                String major = subExcelEntities.get(i).getMajor();
//                String grade = subExcelEntities.get(i).getGrade();
//                String classname = subExcelEntities.get(i).getClassname();
//                String remark = subExcelEntities.get(i).getRemark();
//                map.put("academy" + i, academy);
//                map.put("major" + i, major);
//                map.put("grade" + i, grade);
//                map.put("classname" + i, classname);
//                map.put("remark" + i, remark);
//                list.add(map);
//            }
//            String sheetTitle = "导入失败名单";
//            LinkedHashMap < String, String > linkedHashMap = new LinkedHashMap <>();
//            linkedHashMap.put("academy", "学院");
//            linkedHashMap.put("major", "专业");
//            linkedHashMap.put("grade", "年级");
//            linkedHashMap.put("classname", "班级");
//            linkedHashMap.put("remark", "错误提示");
//            ExportExcel excelExport2 = new ExportExcel();
//            excelExport2.setData(list);
//            excelExport2.setFontSize(12);
//            excelExport2.setSheetName(sheetTitle);
//            excelExport2.setTitle(sheetTitle);
//            excelExport2.setHeader(linkedHashMap);
//            excelExport2.exportExport(request, response);
//        }
//    }
}
